<template>
  <div class="student-management">
    <el-card>
      <div slot="header" class="header">
        <h3>学生管理</h3>
        <el-button type="primary" size="small" @click="handleAdd">添加学生</el-button>
      </div>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item>
          <el-input v-model="queryParams.keyword" placeholder="请输入学号/姓名" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <el-table :data="studentList" border stripe style="width: 100%" v-loading="loading">
        <el-table-column prop="student_id" label="学号" width="120"></el-table-column>
        <el-table-column prop="name" label="姓名" width="100"></el-table-column>
        <el-table-column prop="gender" label="性别" width="60"></el-table-column>
        <el-table-column prop="college" label="学院"></el-table-column>
        <el-table-column prop="major" label="专业"></el-table-column>
        <el-table-column prop="grade" label="年级" width="100"></el-table-column>
        <el-table-column prop="education_level" label="学历" width="100"></el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button type="text" size="small" style="color: #F56C6C;" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 学生编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
      <el-form :model="studentForm" :rules="rules" ref="studentForm" label-width="100px">
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="studentForm.studentId" placeholder="请输入学号"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="studentForm.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="studentForm.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="学院" prop="college">
          <el-input v-model="studentForm.college" placeholder="请输入学院"></el-input>
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-input v-model="studentForm.major" placeholder="请输入专业"></el-input>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input v-model="studentForm.grade" placeholder="请输入年级"></el-input>
        </el-form-item>
        <el-form-item label="班级" prop="className">
          <el-input v-model="studentForm.className" placeholder="请输入班级"></el-input>
        </el-form-item>
        <el-form-item label="入学年份" prop="entryYear">
          <el-date-picker
            v-model="studentForm.entryYear"
            type="year"
            placeholder="选择入学年份"
            value-format="yyyy">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="学历层次" prop="educationLevel">
          <el-select v-model="studentForm.educationLevel" placeholder="请选择学历层次">
            <el-option label="本科" value="本科"></el-option>
            <el-option label="硕士" value="硕士"></el-option>
            <el-option label="博士" value="博士"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="studentForm.phone" placeholder="请输入电话"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="studentForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 学生详情对话框 -->
    <el-dialog title="学生详情" :visible.sync="detailVisible" width="50%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="学号">{{ studentDetail.studentId }}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{ studentDetail.name }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ studentDetail.gender }}</el-descriptions-item>
        <el-descriptions-item label="电话">{{ studentDetail.phone }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ studentDetail.email }}</el-descriptions-item>
        <el-descriptions-item label="学院">{{ studentDetail.college }}</el-descriptions-item>
        <el-descriptions-item label="专业">{{ studentDetail.major }}</el-descriptions-item>
        <el-descriptions-item label="年级">{{ studentDetail.grade }}</el-descriptions-item>
        <el-descriptions-item label="班级">{{ studentDetail.className }}</el-descriptions-item>
        <el-descriptions-item label="入学年份">{{ studentDetail.entryYear }}</el-descriptions-item>
        <el-descriptions-item label="学历层次">{{ studentDetail.educationLevel }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'StudentManagement',
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: ''
      },
      // 学生列表
      studentList: [],
      // 总记录数
      total: 0,
      // 对话框标题
      dialogTitle: '',
      // 对话框可见性
      dialogVisible: false,
      // 详情对话框可见性
      detailVisible: false,
      // 操作类型（add/edit）
      operationType: '',
      // 学生表单
      studentForm: {
        id: null,
        studentId: '',
        name: '',
        gender: '男',
        college: '',
        major: '',
        grade: '',
        className: '',
        entryYear: '',
        educationLevel: '本科',
        phone: '',
        email: '',
        advisorId: null
      },
      // 学生详情
      studentDetail: {},
      // 表单验证规则
      rules: {
        studentId: [
          { required: true, message: '请输入学号', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        college: [
          { required: true, message: '请输入学院', trigger: 'blur' }
        ],
        major: [
          { required: true, message: '请输入专业', trigger: 'blur' }
        ],
        grade: [
          { required: true, message: '请输入年级', trigger: 'blur' }
        ],
        entryYear: [
          { required: true, message: '请选择入学年份', trigger: 'change' }
        ],
        educationLevel: [
          { required: true, message: '请选择学历层次', trigger: 'change' }
        ]
      },
      // 加载状态
      loading: false
    }
  },
  created() {
    this.getStudentList()
  },
  methods: {
    // 获取学生列表
    getStudentList() {
      // 获取当前登录用户ID
      const userInfoStr = window.sessionStorage.getItem('userInfo')
      if (!userInfoStr) {
        this.$message.error('请先登录')
        this.$router.push('/login')
        return
      }
      
      const userInfo = JSON.parse(userInfoStr)
      console.log('当前登录用户信息:', userInfo)
      
      if (!userInfo || !userInfo.id) {
        this.$message.error('用户信息不完整，请重新登录')
        this.$router.push('/login')
        return
      }
      
      // 显示加载状态
      this.loading = true
      
      // 获取当前导师ID下的学生
      request.get('/student/list', {
        params: {
          advisorId: userInfo.id,
          keyword: this.queryParams.keyword
        }
      }).then(res => {
        this.loading = false
        console.log('获取学生列表响应:', res)
        if (res.code === 200) {
          this.studentList = res.data || []
          this.total = this.studentList.length
        } else {
          this.$message.error(res.msg || '获取学生列表失败')
        }
      }).catch(err => {
        this.loading = false
        console.error('获取学生列表错误:', err)
        // 如果后端服务未启动，显示本地提示
        this.studentList = []
        this.total = 0
        this.$message.error('获取学生列表失败，请确保后端服务已启动')
      })
    },
    // 处理搜索
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getStudentList()
    },
    // 重置搜索条件
    resetQuery() {
      this.queryParams.keyword = ''
      this.handleQuery()
    },
    // 处理分页大小改变
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getStudentList()
    },
    // 处理页码改变
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getStudentList()
    },
    // 添加学生
    handleAdd() {
      this.dialogTitle = '添加学生'
      this.operationType = 'add'
      this.resetForm()
      this.dialogVisible = true
      
      // 设置默认导师ID
      const userInfo = JSON.parse(window.sessionStorage.getItem('userInfo'))
      if (userInfo) {
        this.studentForm.advisorId = userInfo.id
      }
    },
    // 编辑学生
    handleEdit(row) {
      this.dialogTitle = '编辑学生'
      this.operationType = 'edit'
      this.dialogVisible = true
      
      // 获取学生详情
      request.get(`/student/detail/${row.id}`).then(res => {
        if (res.code === 200) {
          this.studentForm = res.data
        }
      })
    },
    // 查看学生详情
    handleView(row) {
      request.get(`/student/detail/${row.id}`).then(res => {
        if (res.code === 200) {
          this.studentDetail = res.data
          this.detailVisible = true
        }
      })
    },
    // 删除学生
    handleDelete(row) {
      this.$confirm('确认删除该学生?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        request.delete(`/student/delete/${row.id}`).then(res => {
          this.loading = false;
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.getStudentList()
          } else {
            this.$message.error(res.msg || '删除失败')
          }
        }).catch(error => {
          this.loading = false;
          console.error('删除学生错误:', error);
          this.$message.error('删除学生失败，请确保后端服务已启动');
        });
      }).catch(() => {
        // 取消删除，不做任何操作
      });
    },
    // 重置表单
    resetForm() {
      this.studentForm = {
        id: null,
        studentId: '',
        name: '',
        gender: '男',
        college: '',
        major: '',
        grade: '',
        className: '',
        entryYear: '',
        educationLevel: '本科',
        phone: '',
        email: '',
        advisorId: null
      }
      if (this.$refs.studentForm) {
        this.$refs.studentForm.resetFields()
      }
    },
    // 提交表单
    submitForm() {
      this.$refs.studentForm.validate(valid => {
        if (valid) {
          const formData = {...this.studentForm};
          
          // 确保entryYear是字符串类型
          if (formData.entryYear) {
            formData.entryYear = formData.entryYear.toString();
          }
          
          // 确保advisorId是数字类型
          if (formData.advisorId) {
            formData.advisorId = Number(formData.advisorId);
          }
          
          console.log('提交的学生数据:', formData);
          
          this.loading = true;
          
          if (this.operationType === 'add') {
            // 添加学生
            request.post('/student/add', formData).then(res => {
              this.loading = false;
              if (res.code === 200) {
                this.$message.success('添加成功')
                this.dialogVisible = false
                this.getStudentList()
              } else {
                this.$message.error(res.msg || '添加失败')
              }
            }).catch(error => {
              this.loading = false;
              console.error('添加学生错误:', error);
              this.$message.error('添加学生失败，请确保后端服务已启动');
            });
          } else {
            // 编辑学生
            request.put('/student/update', formData).then(res => {
              this.loading = false;
              if (res.code === 200) {
                this.$message.success('更新成功')
                this.dialogVisible = false
                this.getStudentList()
              } else {
                this.$message.error(res.msg || '更新失败')
              }
            }).catch(error => {
              this.loading = false;
              console.error('更新学生错误:', error);
              this.$message.error('更新学生失败，请确保后端服务已启动');
            });
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.student-management {
  padding: 20px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.search-form {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
</style> 